/*
 * SvcRepairBatch.java
 *
 * Created on April 3, 2007, 5:27 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.group1E.handlers;

import edu.byu.isys413.group1E.data.CustomerBO;
import edu.byu.isys413.group1E.data.ProductBO;
import edu.byu.isys413.group1E.data.RevenueSourceBO;
import edu.byu.isys413.group1E.data.SaleBO;
import edu.byu.isys413.group1E.data.SaleDAO;
import edu.byu.isys413.group1E.data.SvcRepairBO;
import edu.byu.isys413.group1E.data.SvcRepairDAO;
import edu.byu.isys413.group1E.data.TransLineBO;
import edu.byu.isys413.group1E.data.TransLineDAO;
import edu.byu.isys413.group1E.data.TransactionBO;
import edu.byu.isys413.group1E.data.TransactionDAO;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

/** This class handles the batch processing for the Service/Repair transactions, including 
 *notification of repair completion and subsequent notifications.
 *
 * @author tkulbeth
 */
public class SvcRepairBatch {
    /**
     * Contains an instance of SvcRepairBatch
     */
    private static SvcRepairBatch instance = null;
    
    /**
     * Creates a new instance of SvcRepairBatch
     */
    public SvcRepairBatch() {
    }
    
    /**
     * Retrieves an instance of the SvcRepairBatch object
     *
     * @return instance of SvcRepairBatch
     */
    public static synchronized SvcRepairBatch getInstance() {
        if (instance == null) {
            instance = new SvcRepairBatch();
        }
        return instance;
    }
    
    
    /**
     * Creates a new backup revenue source that contains the information
     * needed from the GUI.
     * @throws java.lang.Exception to catch any errors in the process
     */
    public synchronized void processBatch() throws Exception{
        //read in all of the members\
        ArrayList<RevenueSourceBO> srList = SvcRepairDAO.getInstance().readAll();
        
        //get today's date for the begin date
        Calendar cal = Calendar.getInstance();
        java.util.Date today = cal.getTime();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = fmt.format(today);
        Date now = Date.valueOf(todayDate);
        Date dateComplete = null;
        Date lastNotice = null;
        
        System.out.println("\nBeginning repair notification checks: ");
        System.out.println("========================================================");
        for(int t=0;t<srList.size(); t++){
            SvcRepairBO sr = (SvcRepairBO)srList.get(t);
            if(sr.getPickUpDate() != null){     //if the product has been picked up
                return;
            }else{
                if(sr.getCompleteDate() == null){   //if the repair is complete
                    return;
                }else{
                    dateComplete = Date.valueOf(sr.getCompleteDate());  //otherwise get the completion date
                    int compDiff = getMonthDifference(todayDate, sr.getCompleteDate());
                    if(compDiff > 30){
                        if(sr.getLastNoticeDate() != null){
                            lastNotice = Date.valueOf(sr.getLastNoticeDate());
                            int notDiff = getDayDifference(todayDate, sr.getLastNoticeDate());
                            if(notDiff > 3){
                                CustomerBO cust = this.getTransactionDate(sr.getProduct());
                                System.out.println("\n----------------------------------");
                                System.out.println("Customer " + cust.getCustFullName() + " needs to pick up their item.");
                                System.out.println("The following e-mail was generated and sent:\n\n***********\n" +
                                        this.generateEmail(cust, sr.getCompleteDate()) + "\n\n***********");
                                
                            }
                        }
                        
                    }
                }
                
            }
        }
    }
    
    /** Calculates the difference (in days) between two dates by the month.
     *@param dt1 contains one date
     *@param dt2 contains the other date
     *@return the difference (in days)
     */
    private int getMonthDifference(String dt1, String dt2){
        int diff = 0;
        int dt1Month = Integer.parseInt(dt1.substring(5,7));
        int dt2Month = Integer.parseInt(dt2.substring(5,7));
        if(dt1Month < dt2Month){
            diff = ((12 - dt2Month) + dt1Month) * 30;
        }else{
            diff = (dt1Month - dt2Month) * 30;
        }
        return diff;
    }
    
    /** Calculates the difference (in days) between two days.
     *@param dt1 contains one date
     *@param dt2 contains the other date
     *@return the difference (in days)
     */
    private int getDayDifference(String dt1, String dt2){
        int diff = 0;
        int dt1Day = Integer.parseInt(dt1.substring(8,10));

//        System.out.println("months: " + months);
//        System.out.println("add years: " + addYears);
        int dt2Day = Integer.parseInt(dt2.substring(8,10));

        if(dt1Day < dt2Day){
            diff = (30 - dt2Day) + dt1Day;
        }else{
            diff = dt1Day - dt2Day;
        }
        return diff;
    }
    
    /**
     * This method generates a string in a suitable format for an e-mail
     * @param cust contains the customer object from which information will be drawn for the email.
     * @param date contains the date to be included in the e-mail.
     * @return the email contents.
     */
    private String generateEmail(CustomerBO cust, String date){
        String email = new String("Email to: " + cust.getCustEmail() + "\n\nDear " + cust.getCustFullName() + ", \n\n" +
                "This email is a notification that the product you have left at " +
                "\"MyStuff Digital Life\" has been repaired and is available for pickup " +
                "as of " + date + ".\nPlease reclaim your product as soon as possible at the correct location. " +
                "\n\nSincerely, \nMyStuff Digital Life Management");
        return email;
    }
    
    /**
     * Gets the transaction for the repair to find the customer with.
     * 
     * @param prod product to be queried in the database to find the customer and transactionDate
     * @throws java.lang.Exception to catch any errors
     * @return a CustomerBO
     */
    public CustomerBO getTransactionDate(ProductBO prod) throws Exception{
        ArrayList<RevenueSourceBO> sales = SaleDAO.getInstance().readByProductID(prod.getProductID());
        String date = null;
        CustomerBO cust = null;
        //get the first element of the array, since the request was for a physical product
        if(sales.isEmpty() == false){
            SaleBO sale = (SaleBO)sales.get(0);
            TransLineBO txLine = TransLineDAO.getInstance().readByRevSrc(sale.getRevSrcID());
//            System.out.println("Sale id: " +  sale.getRevSrcID());
            TransactionBO tx = TransactionDAO.getInstance().read(txLine.getTransactionID());
            cust = tx.getCustomer();
        }
        return cust;
    }
}
